package com.ruoyi.sea.controller;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.sea.domain.LoginVO;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/app/common")
public class AppCommonController {


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @PostMapping("/login")
    public AjaxResult appLogin(@RequestBody LoginVO loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.appLogin(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    //注册
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody LoginVO user) {
        SysUser sysUser = new SysUser();
        sysUser.setNickName(user.getUsername());
        sysUser.setUserName(user.getUsername());
        if (UserConstants.NOT_UNIQUE == userService.checkUserNameUnique(sysUser)) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，用户账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (userService.registerUser(sysUser)) {
            return AjaxResult.success("注册成功");
        } else {
            return AjaxResult.error("注册失败，请联系系统管理人员");
        }
    }
}
